package org.dreamwork.android.persistence;

import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.Gson;

/**
 * Created by game on 2016/9/7
 */
public abstract class ParcelableObject implements Parcelable {
    protected abstract void copy (ParcelableObject dbo);

    protected ParcelableObject (Parcel in) {
        ParcelableObject dbo = parse (in, getClass ());
        copy (dbo);
    }

    protected<T extends ParcelableObject> T parse (Parcel in, Class<T> type) {
        try {
            int length = in.readInt ();
            byte[] buff = new byte[length];
            in.readByteArray (buff);
            return new Gson ().fromJson (new String (buff, "utf-8"), type);
        } catch (Exception ex) {
            ex.printStackTrace ();
            throw new RuntimeException (ex);
        }
    }

    @Override
    public int describeContents () {
        return 0;
    }

    @Override
    public void writeToParcel (Parcel dest, int flags) {
        try {
            String content = new Gson ().toJson (this);
            byte[] buff = content.getBytes ("utf-8");
            dest.writeInt (buff.length);
            dest.writeByteArray (buff);
        } catch (Exception ex) {
            ex.printStackTrace ();
            throw new RuntimeException (ex);
        }
    }
}